package tp.pr4.instructions;

import java.util.StringTokenizer;
import tp.pr4.NavigationModule;
import tp.pr4.RobotEngine;
import tp.pr4.instructions.exceptions.InstructionExecutionException;
import tp.pr4.instructions.exceptions.WrongInstructionFormatException;
import tp.pr4.items.ItemContainer;

/**
 * Its execution request the robot to finish the simulation This Instruction works 
 * if the user writes QUIT or SALIR
 * @author Alvaro Saez Hernando
 * @author Noel Clemente Montero 
 */
public class QuitInstruction implements Instruction {

	private RobotEngine robot;
	private static final String LINE_SEPARATOR = System.lineSeparator();
	
	/**
	 * Parsers the String returning an instance of QuitInstruction or throwing a 
	 * WrongInstructionFormatException()
	 * @param cad text String to parse
	 * @return Instruction reference to an instance of QuitInstruction
	 * @throws WrongInstructionFormatException When the String is not QUIT | SALIR
	 */
	public Instruction parse(String cad) throws WrongInstructionFormatException {
		
		StringTokenizer st = new StringTokenizer(cad, " ");
		String words = st.nextToken().toUpperCase();
		
		if ((words.equals("QUIT")) || (words.equals("SALIR"))) {
			if (!st.hasMoreTokens())
				return new QuitInstruction();
			else
				throw new WrongInstructionFormatException("WALL·E says: I do not understand. Please repeat" + LINE_SEPARATOR);
		} else
			throw new WrongInstructionFormatException("WALL·E says: I do not understand. Please repeat" + LINE_SEPARATOR);
	}

	/**
	 * Returns a description of the Instruction syntax. The string does not end 
	 * with the line separator. It is up to the caller adding it before printing.
	 * @return the Instruction syntax QUIT|SALIR
	 */
	public String getHelp() {
		return "QUIT|SALIR <id>" + LINE_SEPARATOR;
	}

	/**
	 * Set the execution context. The method receives the entire engine (engine, 
	 * navigation and the robot container) even though the actual implementation of execute() may not require it.
	 * @param engine The robot engine
	 * @param navigation The information about the game, i.e., the places, current 
	 * direction and current heading to navigate
	 * @param robotContainer The inventory of the robot 
	 */
	public void configureContext(RobotEngine engine, NavigationModule navigation, ItemContainer robotContainer) {
		this.robot = engine;
	}

	/**
	 * Request the robot to stop the simulation
	 * @throws InstructionExecutionException if there exist any execution error.
	 */
	public void execute() throws InstructionExecutionException {
		robot.requestQuit();
		System.out.println("WALL·E says: I have communication problems. Bye Bye");
		
	}

}
